import React, { useEffect, useState } from "react";
import { DownOutlined } from "@ant-design/icons";
import { Breadcrumb, Avatar, Space, Dropdown } from "antd";
import { getUserInfo } from '@/api/users';
import './index.less';
import { baseUrl } from '@/utile/commen';
// 使用 redux 的状态和 actions
// useSelector 获取状态
// useDispatch 获取 actions
import { useSelector, useDispatch } from "react-redux";
import { changeInfor } from "@/store/userSlice";
import { NavLink, useLocation, Link } from "react-router-dom";


export default function AppHeader() {
  const userInfo = useSelector(state => state.user.userInfor);
  const dispatch = useDispatch();
  const location = useLocation();

  const getInfor = async () => {
    const user = sessionStorage.getItem('user');
    if (user) {
      const id = JSON.parse(user).id;
      if (id) {
        const res = await getUserInfo({ id });
        dispatch(changeInfor(res.accountInfo));
      }
      console.log(location);
    }

  };

  useEffect(() => {
    getInfor();
  }, []);

  const items = [
    {
      key: '1',
      label: (
        <NavLink to={'/home/accountCenter'}>
          个人中心
        </NavLink>
      ),
    },
    {
      key: '2',
      label: (
        <NavLink
          to={'/'}
          onClick={() => {
            sessionStorage.clear();
            dispatch(changeInfor(null));
          }}
        >
          退出登录
        </NavLink>
      ),
    },
  ];

  const breadcrumbNameMap = {
    '/home': '首页',
    '/home/accountList': '用户列表',
    '/home/accountAdd': '新增用户',
    '/home/accountEdit': '编辑用户',
    '/home/accountCenter': '个人中心',
    '/home/goodsList': '商品列表',
    '/home/goodsAdd': '新增商品',
    '/home/goodsType': '商品分类',
    '/home/orderList': '订单管理',
    '/home/shopInfo':'店铺管理',
    '/home/goosStatistics':'商品统计',
    '/home/orderStatistics':'订单统计',
    '/home/permissionInfo':'权限管理',
    '/home/rolePermission':'角色管理'
  };

  const pathSnippets = location.pathname.split('/').filter(i => i);
  const addedParents = { user: false, goods: false,promise:false,statistics:false }; // 父级标记

  const extraBreadcrumbItems = pathSnippets
    .map((_, index) => {
      const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
      return { url, snippet: pathSnippets[index] };
    })
    .filter(({ url }) => url !== "/home") // 排除home路径
    .flatMap(({ url, snippet }) => {
      const items = [];

      // 检测用户管理模块
      if (url.startsWith('/home/account') && !addedParents.user) {
        items.push(
          <Breadcrumb.Item key="userManagement">用户管理</Breadcrumb.Item>
        );
        addedParents.user = true;
      }

      // 检测商品管理模块
      if (url.startsWith('/home/goods') && !addedParents.goods) {
        items.push(
          <Breadcrumb.Item key="goodsManagement">商品管理</Breadcrumb.Item>
        );
        addedParents.goods = true;
      }
      // 检测数据统计模块
      if ((url.startsWith('/home/goosStatistics') ||(url.startsWith('/home/orderStatistics')))&& !addedParents.statistics) {
        items.push(
          <Breadcrumb.Item key="goodsManagement">权限管理</Breadcrumb.Item>
        );
        addedParents.statistics = true;
      }

      // 检测权限管理模块
      if ((url.startsWith('/home/rolePermission') ||(url.startsWith('/home/permissionInfo')))&& !addedParents.promise) {
        items.push(
          <Breadcrumb.Item key="goodsManagement">统计数据</Breadcrumb.Item>
        );
        addedParents.promise = true;
      }

      // 添加当前路径项
      const displayName = breadcrumbNameMap[url] || snippet;
      items.push(
        <Breadcrumb.Item key={url}>
          <Link to={url}>{displayName}</Link>
        </Breadcrumb.Item>
      );

      return items;
    });
  return (
    <div className="header">
      <Breadcrumb separator=">">
        {/* 手动添加首页且唯一 */}
        <Breadcrumb.Item key="home">
          <Link to="/home">首页</Link>
        </Breadcrumb.Item>
        {/* 动态生成其他层级 */}
        {extraBreadcrumbItems}
      </Breadcrumb>
      <div>
        <Dropdown menu={{ items }}>
          <Space>
            欢迎 {userInfo.account} 登录 <DownOutlined />
          </Space>
        </Dropdown>
        <Space>
          <Avatar src={baseUrl + userInfo.imgUrl} />
        </Space>
      </div>
    </div>
  );
}
